var backLogState = {"回收站": "0", "待办": "1", "进行": "2", "完成": "3", "发布": "4"};
var overTime = $(".setUp", parent.document).attr("name");
var getBackLogState = true;

$(document).ready(function () {
    doGetAllProducts('productPackUp', 'backLogProducts', 'productUnfurled');
    doGetAllMembers('memberPackUp', 'backLogMembers', 'memberUnfurled');
    getBackLogByUser("",2);
    doGetAllUpdateMembers();
    addDrag();
});
function touchEvent(){
    var backLogsDiv = $("#backLogContent>div");
    for(var i = 0 ; i < backLogsDiv.length ; i++){
        $(backLogsDiv[i]).on({
            touchstart: function(e){
                timeOutEvent = setTimeout("longPress("+e.currentTarget.id+")",500);
                e.preventDefault();
            },
            touchmove: function(){
                clearTimeout(timeOutEvent);
                timeOutEvent = 0;
            },
            touchend: function(){
                clearTimeout(timeOutEvent);
                if(timeOutEvent!=0){
                    alert("你这是点击，不是长按");
                }
                   return false;
            }
        })
    }
}
function longPress(currentID){
    timeOutEvent = 0;
    $("#UpdateBackLogDiv").show();
    var stateList = $("#UpdateState>.stateList");
     for(var i = 0 ; i < stateList.length ; i++){
        $(stateList[i]).attr("onclick","doUpdateBackLogState(\'"+currentID+"\',\'"+$(stateList[i]).attr("id")+"\')");
    }
     var updateMemberList = $("#UpdateMemberMenu>.updateMemberList");
        for(var i = 0 ; i < updateMemberList.length ; i++){
            $(updateMemberList[i]).attr("onclick","doUpdateBackLogUser(\'"+currentID+"\',\'"+$(updateMemberList[i]).attr("id")+"\')");
    }
}
function addDrag() {
    var li = $("#backLogNavigation ul li span");
    for (var i = 0; i < li.length; i++) {
        if (li[i].innerHTML != "全部") {
            li[i].setAttribute('ondragenter', 'dragEnter(event)');
            li[i].setAttribute('ondragleave', 'dragLeave(event)');
            li[i].setAttribute('ondrop', 'drop(event)');
            li[i].setAttribute('ondragover', 'allowDrop(event)');
            li[i].setAttribute('class', 'droptarget commonBlueFont');
        }
    }
}
function doGetAllUpdateMembers(){
    $.post("doGetAllMembers",function (result) {
        if(result.state==1){
            var list=result.data;
            var UpdateMemberMenu = $("#UpdateMemberMenu");
            UpdateMemberMenu.empty();
            for(var i in list){
                UpdateMemberMenu.append('<p class="updateMemberList hoverPointer" id="'+list[i].userID+'">'+list[i].userName+'</p>');
            }
        }else{
            showMessage("获取成员失败");
        }
    });
}
function doGetAllProducts(OneElement, TwoElement, ThreeElement) {
    $.post("doGetAllProducts",function (result) {
        if (result.state == 1) {
            var list = result.data;
            var backLogProducts = $("#backLogProducts");
            backLogProducts.empty();
            for (var i in list) {
                var productInitials = list[i].productName.substring(0, 1);
                backLogProducts.append('<div class="productList">' +
                    '<span class="productLabel">' + productInitials + '</span>' +
                    '<span id="' + list[i].productName + '1" class="productName commonBlueFont" onMouseOver="mmigration(\'' + list[i].productName + '1\')" onMouseOut="shiftOut()"' +
                    ' onclick="doGetProductVersion(\'' + list[i].productId + '\',\'' + list[i].productName + '1\',\'' + list[i].productName + '2\')">' + list[i].productName +
                    '<img  src="../PM/images/arrow1.png"  />' +
                    '</span>' +
                    '<span id="' + list[i].productName + '2" class="productName commonBlueFont"  onMouseOver="mmigration(\'' + list[i].productName + '2\')" onMouseOut="shiftOut()"' +
                    ' onclick="toCloseVersions(\'' + list[i].productId + '\',\'' + list[i].productName + '2\',\'' + list[i].productName + '1\')" hidden="hidden">' + list[i].productName +
                    '<img  src="../PM/images/arrow2.png"/>' +
                    '</span>' +
                    '<div class="productEditions" id="' + list[i].productId + '"></div></div>');
            }
            $("#" + ThreeElement).hide();
            $('#' + OneElement).show();
            $('#' + TwoElement).show();
        } else {
            showMessage("获取产品失败");
        }
    });
}
function toCloseVersions(productId, OneElement, TwoElement) {
    $("#" + OneElement).hide();
    $("#" + TwoElement).show();
    $("#" + productId).hide();
}
function getBackLog(backLogState, OneElement) {
    var productVersionId = '';
    var MemberId = '';
    productVersionId = getProductVersionId();
    MemberId = getMemberId();

    $('.activeLi').removeClass("activeLi");
    $("#" + OneElement).addClass("activeLi");

    var params = {"productVersionId": productVersionId, "MemberId": MemberId, "BacklogStatus": backLogState};
    $.post("doGetBackLog", params, function (result) {
        if (result.state) {
            buildBackLog(result.data);
        } else {
            showMessage("获取所有BackLog失败");
        }
    });
}
function doGetProductVersion(productId, OneElement, TwoElement) {
    var $div = $("#" + productId);
    $div.show();
    $div.empty();
    var params = {"productId": productId};
    $.post("doGetProductVersions", params, function (result) {
        if (result.state) {
            var list = result.data;
            for (var i in list) {
                $div.append('<p id=\'' + list[i].productVersionID + '\' class="commonBlueFont" onMouseOver="mmigration(\'' + list[i].productVersionID + '\')" onMouseOut="shiftOut()" ' +
                    'onclick="getAllData(\'' + list[i].productVersionID + '\')">' + list[i].productVersionName + '</p>');
            }
            $("#" + OneElement).hide();
            $("#" + TwoElement).show();
        } else {
            showMessage("获取产品版本信息失败");
        }
    });
}
function getbackLogFeed() {
    var backLogId = '';
    var backLogContent = $("#backLogContent").children();
    if (backLogContent) {
        for (var i = 0; i < backLogContent.length; i++) {
            if (backLogId == '') {
                backLogId += backLogContent[i].id;
            } else {
                backLogId += "," + backLogContent[i].id;
            }
        }
    }
    $.post("doGetbackLogFeed", {"backLogId": backLogId}, function (result) {
        if (result.state == 1) {
            buildFeedBack(result.data);
        } else {
            showMessage("获取所有反馈失败");
        }
    })
}
function doPunch(backLogId) {
    var $userName = defaultID;
    $.post("getUserIDByBackLogID", {"backLogId": backLogId}, function (result) {
        if (result.state == 1) {
            if (result.data == 1) {
                $.post("getPunchEveryDay", {"backLogId": backLogId}, function (result) {
                    if (result.state == 1) {
                        if (result.data == 0) {
                            $.post("updatePunchTime", {"backLogId": backLogId}, function (result) {
                                if (result.state == 1) {
                                    var $backLogNavigation = $("#backLogNavigation ul li span");
                                    for (var i = 0; i < $backLogNavigation.length; i++) {
                                        if ($backLogNavigation[i].className.indexOf("activeLi") >= 0) {
                                            if($backLogNavigation[i].id == "conduct"){
                                                $("#conduct").click();
                                            }else if($backLogNavigation[i].id == "whole"){
                                                $("#whole").click();
                                            }
                                        }
                                    }
                                    $.post("doAddPunchRecord", {"backLogId": backLogId}, function (result) {
                                        if (result.state != 1) {
                                            showMessage("打卡数据未更新");
                                        }
                                    });
                                    $("#ModalBody").html("打卡成功");
                                    $("#showModal").show();
                                    setTimeout("closeModal('showModal')", 1500);
                                } else {
                                    showMessage("打卡失败");
                                }
                            });
                        } else {
                            showMessage("今日已打卡");
                        }
                    } else {
                        showMessage("获取打卡数据失败");
                    }
                });
            } else {
                showMessage("只能给自己打卡");
            }
        } else {
            showMessage("获取用户信息失败");
        }
    });
}
function getAllData(productVersionID) {

    $('.activeLi').removeClass("activeLi");
    $('.activeP').removeClass("activeP");
    $('.activeSpan').removeClass("activeSpan");
    $("#" + productVersionID).addClass("activeP");
    $("#whole").addClass("activeLi");

    $.post("doGetFeedByProductVersionId", {"$productVersionId": productVersionID}, function (result) {
        if (result.state == 1) {
            buildFeedBack(result.data);
        } else {
            showMessage("获取版本号反馈失败");
        }
    });
    $.post("doGetBackLogByProductVersionId", {"$productVersionId": productVersionID}, function (result) {
        if (result.state == 1) {
            buildBackLog(result.data);
        } else {
            showMessage("获取版本号BackLog失败");
        }
    });
    updateCurrentTitle(productVersionID);
     doneEffect();
}
function updateCurrentTitle(productVersionID){
    $.post("doGetCurrentTitle", {"$productVersionId": productVersionID}, function (result) {
            if (result.state == 1) {
             var list = result.data;
                var currentTitle = $("#currentTitle");
                currentTitle.empty();
                currentTitle.html(list[0].productName+"-"+list[0].productVersionName);
            } else {
                showMessage("获取当前页面位置失败");
            }
     });
}
function buildFeedBack(list) {
    var backLogFeedLists = $("#backLogFeedLists");
    var backLogFeedNumber = $("#backLogFeedNumber");
    backLogFeedNumber.empty();
    backLogFeedLists.empty();
    var $div = '<div class="FeedList"><span>[CreateTime]</span>' +
        '<span>[FeedBackDescription]</span>' +
        '<span id="backLogFeedName[FeedBackId]">[UserName]</span></div>';
    if (list.length > 0) {
        $(backLogFeedNumber).html("目前你有" + list.length + "条反馈未解决");
        $("#backLogModular").css("height","75%");
        if(list.length == 1){
            $("#backLogFeed").css("height","12%");
        }else  if(list.length == 2){
            $("#backLogFeed").css("height","15%");
        }else  if(list.length == 3){
            $("#backLogFeed").css("height","18%");
        }else{
            $("#backLogFeed").css("height","17%");
        }
    } else {
        $(backLogFeedNumber).html("当前没有反馈");
        $("#backLogFeed").css("height","");
        $("#backLogModular").css("height","84%");
    }
    for (var i in list) {
        var createTime = formatDate(list[i].CreateDTTM);
        backLogFeedLists.append($div.replace('[CreateTime]', createTime)
            .replace('[FeedBackDescription]', list[i].FeedBackDescription)
            .replace('FeedBackId', list[i].FeedBackID)
            .replace('[UserName]', list[i].UserName))
    }
}
function buildBackLog(list) {
    var backLogContent = $("#backLogContent");
    backLogContent.empty();
    for (var i in list) {
        var expectedSpan = '';
        var doPunchP = '';
        var timeSituation = '';
        if (list[i].stateName == "进行") {
            doPunchP = '<p  onclick="doPunch(\'' + list[i].backLogID + '\')" id="doPunch"><img src="../PM/images/punch.png"> 打卡</p>';
            expectedSpan = '<span class="expectedTIME">' + formatDate(list[i].expectedStartDTTM)+ '</span>';
            if (list[i].timeSituation < 0) {
                timeSituation = '<p class="backLogSign" id="overtime"><a>延</a></p>';
            } else if (list[i].timeSituation <= overTime) {
                timeSituation = '<p class="backLogSign" id="emergency"><a>急</a></p>';
            }
        } else if (list[i].stateName == "待办") {
            expectedSpan = '<span class="expectedTIME">' + formatDate(list[i].expectedStartDTTM)+ '</span>';
            if (list[i].timeSituation < 0) {
                timeSituation = '<p class="backLogSign" id="overtime"><a>延</a></p>';
            } else if (list[i].timeSituation <= overTime) {
                timeSituation = '<p class="backLogSign" id="emergency"><a>急</a></p>';
            }
        }
        backLogContent.append(
            '<div class="col-sm-2  State' + list[i].backLogStatus + '" id="' + list[i].backLogID + '" ondragstart="dragStart(event)" ondragleave="dragLeave(event)" draggable="true" ondrop="drop(event)" onmouseover="addBoxShadow(\'' + list[i].backLogID + '\',\'' + list[i].backLogStatus + '\')" onmouseout="clearBoxShadow(\'' + list[i].backLogID + '\',\'' + list[i].backLogStatus + '\')">' +
            '<p class="updateBackLog" id="updateBackLog'+list[i].backLogID+'" onclick="updateBackLog(\''+list[i].backLogID+'\')">修改</p>'+
            '<p class="backLogContentTop">' + (list[i].moduleName || "已删除") + "-" + list[i].backLogName + '</p>' +
            '<p class="backLogContentState">状态 : ' +
            '<span><a>' + list[i].stateName + '</a></span>' + expectedSpan +
            '</p>' +
            '<p class="backLogExpected">预期 : ' +
            '<span><a>' + list[i].expectedWorkDate + '天</a></span>' +
            '</p>' +
            '<p class="backLogActual">实际 : ' +
            '<span><a>' + list[i].actualWorkDate + '天</a></span>' +
            '</p>' + timeSituation + doPunchP +
            '<p class="backLogSign" id="backLogWorkType"><a>' + list[i].workTypeNameSign + '</a></p>' +
            '</div>');
    }
    touchEvent();
}
function updateBackLog(backLogID){
    $(".addBackLog").show();

}
function hideBackLogMsg() {
    $(".addBackLog").hide();
}
function getBackLogByUser($MemberID,BacklogStatus) {
    $('.activeLi').removeClass("activeLi");
    $('.activeSpan').removeClass("activeSpan");
    $("#whole").addClass("activeLi");
    var productVersionId = getProductVersionId();
    var userID='';
    if($MemberID){
        userID=$MemberID;
    }
    var params = {"UserID": userID, "ProductVersionID": productVersionId, "BackLogStatus": BacklogStatus};
    $.post("doGetBackLogByUser", params, function (result) {
        if (result.state) {
            buildBackLog(result.data);
        } else {
            showMessage("获取所有BackLog失败");
        }
        $("#" + userID + "span").addClass("activeSpan");
        if (getBackLogState == true) {
            getbackLogFeed();
            getBackLogState = false;
        }
        $("#conduct").click();
    });
     doneEffect();
}
function addBoxShadow(ID, State) {
    $("#" + ID).addClass("borderState" + State);
}
function clearBoxShadow(ID, State) {
    $("#" + ID).removeClass("borderState" + State);
}
function getProductVersionId() {
    var productVersionId = '';
    var productVersion = $(".productEditions p");
    for (var i = 0; i < productVersion.length; i++) {
        if (productVersion[i].className.indexOf("activeP") >= 0) {
            productVersionId = productVersion[i].id;
        }
    }
    return productVersionId;
}
function getMemberId() {
    var $MemberId = '';
    var MemberId = $(".memberList").children("span:last-child");
    for (var i = 0; i < MemberId.length; i++) {
        if (MemberId[i].className.indexOf("activeSpan") >= 0) {
            $MemberId = MemberId[i].id.replace("span", "");
        }
    }
    return $MemberId;
}
function doUpdateBackLogState(backLogID, backLogState) {

    $.post("doUpdateBackLogState", {"backLogID": backLogID, "backLogState": backLogState}, function (result) {
        if (result.state == 1) {
            $("#UpdateBackLogDiv").hide();
             var $backLogNavigation = $("#backLogNavigation ul li span");
                  for (var i = 0; i < $backLogNavigation.length; i++) {
                     if ($backLogNavigation[i].className.indexOf("activeLi") >= 0) {
                          $($backLogNavigation[i]).click();
                     }
              }
        } else {
            showMessage(result.message);
        }
    })
}
function  doUpdateBackLogEndDTTM(backLogID, backLogState) {

    $.post("doUpdateBackLogEndDTTM", {"backLogID": backLogID, "backLogState": backLogState}, function (result) {
        if (result.state == 1) {
            showMessage("拖动成功");
        } else {
            showMessage(result.message);
        }
    });
}
function doUpdateBackLogUser(backLogID, UserID) {
    $.post("doUpdateBackLogUser", {"backLogID": backLogID, "UserID": UserID}, function (result) {
        if (result.state == 1) {
            $("#UpdateBackLogDiv").hide();
            var $backLogNavigation = $("#backLogNavigation ul li span");
              for (var i = 0; i < $backLogNavigation.length; i++) {
                 if ($backLogNavigation[i].className.indexOf("activeLi") >= 0) {
                      $($backLogNavigation[i]).click();
                 }
             }
            $.post("sendWorkDataByUserID",{"UserID":UserID},function(result){ })
        } else {
            showMessage(result.message);
        }
    });
}

/*用户开始拖动元素时触发*/
function dragStart(event) {
    event.dataTransfer.setData("Text", event.target.id);
    $("#Agency").css("background-color", "rgba(0,184,191,1)");
    $("#conduct").css("background-color", "rgba(3,201,41,1)");
    $("#complete").css("background-color", "rgba(10,141,209,1)");
    $("#release").css("background-color", "rgba(212,153,13,1)");
    $("#recycleBin").css("background-color", "rgb(255,248,15)");
    $(".memberList").css("background-color", "rgba(146, 146, 146, 0.15)");
    $(".memberList").css("border-bottom", "0.5px solid rgba(35, 33, 33, 0.23)");
}
/*当被鼠标拖动的对象进入其容器范围内时触发此事件*/
function dragEnter(event) {
    if (event.target.className == "memberList") {
        event.target.style.height = "60px";
        event.target.style.paddingTop = "20px";
    }
}
/* 当被鼠标拖动的对象离开其容器范围内时触发此事件*/
function dragLeave(event) {
    if (event.target.className == "memberList") {
        event.target.style.height = "auto";
        event.target.style.paddingTop = "0px";
    }
}
/*当某被拖动的对象在另一对象容器范围内拖动时触发此事件*/
function allowDrop(event) {
    event.preventDefault();
}
/*元素正在拖动时触发*/
function drop(event) {
    if (event.target.className == "droptarget commonBlueFont") {
        event.preventDefault();
        var data = event.dataTransfer.getData("Text");
        document.getElementById(data).style.display = 'none';
        if(event.target.innerHTML=="完成"){
            doUpdateBackLogEndDTTM(document.getElementById(data).id, backLogState[event.target.innerHTML]);
        }else{
            doUpdateBackLogState(document.getElementById(data).id, backLogState[event.target.innerHTML]);
        }
    } else if (event.target.className == "memberList") {
        event.preventDefault();
        var data = event.dataTransfer.getData("Text");
        document.getElementById(data).style.display = 'none';
        doUpdateBackLogUser(document.getElementById(data).id, event.target.id);
    }
}
// 当拖完p元素输出一些文本元素和重置透明度
document.addEventListener("dragend", function (event) {
    $("#Agency").css("background-color", "");
    $("#conduct").css("background-color", "");
    $("#complete").css("background-color", "");
    $("#release").css("background-color", "");
    $("#recycleBin").css("background-color", "");
    $(".memberList").css("background-color", "");
    $(".memberList").css("border-bottom", "");
    $(".memberList").css("height", "auto");
    $(".memberList").css("paddingTop", "");
});
